<template>
  <div class="layout">
    <div class="sidebar">
      <!-- 左侧工具栏 -->
      <aside>
        <div v-for="(tool, idx) in tools" :key="tool.name" :class="['tool-btn', { active: idx === activeTool }]"
          @click="handleToolClick(idx, tool)">
          <svg-icon :icon-class="tool.icon" />
          <span class="tooltip">{{ tool.name }}</span>
        </div>
      </aside>
    </div>
    <div class="center" :style="{ width: centerWidth + 'px' }">
      <!-- 中间：好友/聊天列表 -->
      <section class="friends-list">
        <template v-if="chat">
          <div class="header">聊天</div>
          <div class="search-bar">
            <input v-model="search" placeholder="搜索好友" />
          </div>
          <div class="list">
            <div v-for="friend in filteredFriends" :key="friend.id"
              :class="['friend-item', { active: activeFriend && activeFriend.id === friend.id }]"
              @click="selectFriend(friend)">
              <img :src="friend.avatar" class="avatar" />
              <div class="info">
                <div class="top">
                  <span class="name">{{ friend.nickName }}</span>
                  <span class="time">{{ friend.latestMessageTime }}</span>
                </div>
                <div class="last-msg">
                  {{ friendMap[friend.userId].latestMessage[friendMap[friend.userId].latestMessage.length - 1].message }}
                </div>
              </div>
            </div>
          </div>
        </template>
        <template v-else-if="showContacts">
          <div class="contacts-list">
            <div v-if="groupedContacts.length === 0" class="empty">暂无联系人</div>
            <div v-for="group in groupedContacts" :key="group.letter" class="contact-group">
              <div class="group-title">{{ group.letter }}</div>
              <div v-for="friend in group.friends" :key="friend.id" class="contact-item">
                <img :src="friend.avatar" class="avatar" />
                <div class="info">
                  <div class="name">{{ friend.friendRemark }}</div>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template v-else-if="showFriendRequest">
          <div class="friend-request-list">
            <div v-if="friendRequests.length === 0" class="empty">暂无好友申请</div>
            <div v-for="req in friendRequests" :key="req.id" class="friend-request-item">
              <img :src="req.avatar" class="avatar" />
              <div class="info">
                <div class="name">{{ req.nickName }}</div>
                <div class="msg">{{ req.verifyMsg }}</div>
                <div class="meta">
                  <span class="time">{{ formatTime(req.requestTime) }}</span>
                  <span class="status" :class="getStatusClass(req.status)">
                    {{ getStatusText(req.status) }}
                  </span>
                </div>
              </div>
              <div class="remark" @click="showRemarkDialog(req)">
                {{ req.verifyMessage && req.verifyMessage.length > 5 ? req.verifyMessage.slice(0, 5) + '...' :
                  req.verifyMessage }}
              </div>
              <div class="actions">
                <button v-show="!req.isRequestFromMe && req.status === '0'" @click="acceptRequest(req)">同意</button>
                <button v-show="!req.isRequestFromMe && req.status === '0'" @click="rejectRequest(req)">拒绝</button>
              </div>
            </div>
          </div>
        </template>
        <template v-else-if="showAddFriend">
          <div class="add-friend-simple">
            <input v-model="searchUserInput" @keyup.enter="searchUser" placeholder="输入昵称或ID，回车搜索"
              class="search-user-input" />
            <div v-if="searchedUser" class="searched-user-info">
              <img :src="searchedUser.avatar" class="avatar" />
              <span class="name">{{ searchedUser.nickName }}</span>
              <button @click="openAddFriendDialog" :disabled="isFriend(searchedUser)">添加好友</button>
              <span v-if="!searchedUser.addFriendButton" class="already-friend">已是好友</span>
            </div>
            <div v-if="searchUserError" class="error">{{ searchUserError }}</div>
          </div>
        </template>
        <div v-if="searchUserError" class="error">{{ searchUserError }}</div>
      </section>
    </div>
    <div class="drag-bar" @mousedown="startDrag('center')"></div>
    <div class="chat-panel">
      <!-- 右侧：聊天窗口 -->
      <section>
        <div v-if="activeFriend" class="chat-wrapper">
          <div class="chat-header">
            <img :src="activeFriend.avatar" class="avatar" />
            <span class="name">{{ activeFriend.nickName }}</span>
          </div>
          <div class="chat-messages" ref="chatMessages">
            <div v-for="(msg, idx) in friendMap[activeFriend.userId].latestMessage" :key="idx"
              :class="['message', msg.isSender ? 'sent' : 'received']">
              <span class="text">{{ msg.message }}</span>
            </div>
          </div>
          <div class="chat-input">
            <input v-model="input" @keyup.enter="sendMessage" placeholder="请输入消息..." :disabled="!activeFriend" />
            <button @click="sendMessage" :disabled="!input.trim()">发送</button>
          </div>
        </div>
        <div v-else class="chat-empty">
          <span>请选择一个好友开始聊天</span>
        </div>
      </section>
    </div>
    <!-- 添加好友弹窗 -->
    <div v-if="showAddFriendDialog" class="add-friend-dialog-mask">
      <div class="add-friend-dialog">
        <div class="dialog-header">添加好友</div>
        <div class="dialog-body">
          <img :src="searchedUser.avatar" class="avatar" />
          <div class="user-info">
            <span class="name">{{ searchedUser.nickName }}</span>
          </div>
          <div class="input-group">
            <label>备注：</label>
            <input v-model="addFriendRemark" placeholder="请输入备注" />
          </div>
          <div class="input-group">
            <label>验证信息：</label>
            <input v-model="addFriendVerifyMsg" placeholder="请输入验证信息" />
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="confirmAddFriend">确认</button>
          <button @click="showAddFriendDialog = false">取消</button>
        </div>
      </div>
    </div>
    <div v-if="showRemarkDialogVisible" class="remark-dialog-mask">
      <div class="remark-dialog">
        <div class="remark-title">
          好友申请备注
          <span class="remark-close" @click="closeRemarkDialog">×</span>
        </div>
        <div class="remark-content">{{ currentRemarkReq.verifyMessage }}</div>
        <div class="remark-actions">
          <button v-if="!currentRemarkReq.isRequestFromMe && currentRemarkReq.status === '0'"
            @click="acceptRequest(currentRemarkReq)">同意</button>
          <button v-if="!currentRemarkReq.isRequestFromMe && currentRemarkReq.status === '0'"
            @click="rejectRequest(currentRemarkReq)">拒绝</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import pinyin from 'pinyin';
import { addFriendQuery, addFriendRequest, queryFriendRequest, executeFriendRequest, querylatestMessage,queryChatHistory } from '@/api/chat/chat'
import { isSuccess } from '../../utils/response';
import { queryFriend } from '../../api/chat/chat';
import { getWsUrl } from '@/config/websocket';
import { onMounted } from 'vue';
export default {
  name: "WeChatFriends",
  data() {
    return {
      ws: null,
      showRemarkDialogVisible: false,
      currentRemarkReq: null,
      searchUserInput: "",
      searchedUser: null,
      searchUserError: "",
      showAddFriend: false,
      chat: true,
      showFriendRequest: false,
      addFriendName: "",
      addFriendAvatar: "",
      addFriendError: "", activeTool: 0,
      search: "",
      input: "",
      currentUser: "我",
      tools: [
        { name: "聊天", icon: "message" },
        { name: "通讯录", icon: "peoples" },
        { name: "发现", icon: "search" },
        { name: "设置", icon: "system" },
        { name: "添加好友", icon: "eye" },
        { name: "好友申请", icon: "people" }
      ],
      contactList: [
      ],
      friends: [
      ],
      friendMap: {},
      activeFriend: null,
      showAddFriendDialog: false,
      addFriendRemark: '',
      addFriendVerifyMsg: '',
      friendRequests: [], // 好友申请列表
      centerWidth: 320,
      dragging: false,
      dragStartX: 0,
      centerStart: 320,
      minCenterWidths: {
        '聊天': 320,
        '通讯录': 260,
        '发现': 200,
        '设置': 300,
        '添加好友': 280,
        '好友申请': 410
      },
      showContacts: false,
      dataContent: {
        chatMsg: {
          senderId: '',
          receiverId: '',
          msg: '',
          msgType: '',
          msgId: '',
          chatTime: '',
          showMsgDateTimeFlag: ''
        },
        chatTime: '',
        extend: ''
      }
    };
  },

  computed: {
    filteredFriends() {
      console.log("zhc" + this.friends)
      if (!this.search) return this.friends;
      return this.friends.filter(f =>
        f.nickName.includes(this.search)
      );
    },
    currentMinCenterWidth() {
      const toolName = this.tools[this.activeTool]?.name;
      return this.minCenterWidths[toolName] || 200; // 默认200
    },
    groupedContacts() {
      const groups = {};
      (this.contactList || []).forEach(friend => {
        let name = friend.friendRemark || friend.name || '';
        let first = '';
        if (name) {
          // 获取拼音首字母
          const py = pinyin(name[0], { style: pinyin.STYLE_FIRST_LETTER, heteronym: false });
          first = py && py[0] && py[0][0] ? py[0][0].toUpperCase() : '#';
        } else {
          first = '#';
        }
        if (!/^[A-Z]$/.test(first)) first = '#';
        if (!groups[first]) groups[first] = [];
        groups[first].push(friend);
      });
      const sorted = Object.keys(groups).sort().map(letter => ({
        letter,
        friends: groups[letter].sort((a, b) => (a.friendRemark || a.name || '').localeCompare(b.friendRemark || b.name || ''))
      }));
      return sorted;
    }
  },
  methods: {
    async searchUser() {
      this.searchUserError = "";
      this.searchedUser = null;
      if (!this.searchUserInput.trim()) {
        this.searchUserError = "请输入昵称或ID";
        return;
      }
      try {
        addFriendQuery({ 'cond': this.searchUserInput.trim() }).then(response => {
          this.searchedUser = response.data;
        })
        // const res = await axios.get('/zhc/chat/add-friend-query', { params: { cond: this.searchUserInput.trim() } });
        // this.searchedUser = res.data;
      } catch (e) {
        console.log(e)
        this.searchUserError = "查询失败";
      }
    },
    fetchLatestMessage() {
      querylatestMessage().then(response => {
        if (isSuccess(response)) {
          this.friends = response.data
          response.data.forEach(friend => {
            if(!this.activeFriend||this.activeFriend.userId!=friend.userId){
                this.friendMap[friend.userId] = {
                latestMessage: [{
                  message: friend.latestMessage,
                  isSender: friend.isLatestMessageSender
                }],
                unread: 0
              }
            }
            
          })
          console.log("friendMap:" + JSON.stringify(this.friendMap))
        }
      })
    },
    showRemarkDialog(req) {
      this.currentRemarkReq = req;
      this.showRemarkDialogVisible = true;
    },
    closeRemarkDialog() {
      this.showRemarkDialogVisible = false;
      this.currentRemarkReq = null;
    },
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;

      // 如果是今天的消息，显示时间
      if (diff < 24 * 60 * 60 * 1000) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      }
      // 如果是昨天的消息，显示"昨天"
      if (diff < 48 * 60 * 60 * 1000) {
        return '昨天';
      }
      // 如果是今年的消息，显示月日
      if (date.getFullYear() === now.getFullYear()) {
        return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
      }
      // 其他情况显示年月日
      return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
    },
    getStatusText(status) {
      switch (status) {
        case '0':
          return '待处理';
        case '1':
          return '已同意';
        case '2':
          return '已拒绝';
        default:
          return '未知';
      }
    },
    getStatusClass(status) {
      switch (status) {
        case '0':
          return 'pending';
        case '1':
          return 'accepted';
        case '2':
          return 'rejected';
        default:
          return '';
      }
    },
    openAddFriendDialog() {
      this.addFriendRemark = '';
      this.addFriendVerifyMsg = '';
      this.showAddFriendDialog = true;
    },
    confirmAddFriend() {
      this.addSearchedUser(this.addFriendRemark, this.addFriendVerifyMsg);
      this.showAddFriendDialog = false;
    },
    addSearchedUser(remark, verifyMsg) {
      if (!this.searchedUser) return;
      if (this.isFriend(this.searchedUser)) return;
      addFriendRequest(
        { 'remark': remark, 'verifyMsg': verifyMsg, 'userId': this.searchedUser.id, "nickName": this.searchedUser.nickName }).then(response => {
          if (response.code == 200) {
            this.showAddFriend = false;
            this.chat = true;
            this.selectFriend(this.friends[this.friends.length - 1]);
            this.searchUserInput = '';
            this.searchedUser = null;
            this.searchUserError = '';
            this.$modal.msgSuccess("好友申请已发送");
          } else {
            this.searchUserError = response.msg;
          }
        })


    },
    isFriend(user) {
      return this.friends.some(f => f.id === user.id);
    },
    doAddFriend() {
      if (!this.addFriendName.trim()) {
        this.addFriendError = "昵称不能为空";
        return;
      }
      const avatar = this.addFriendAvatar.trim() || "https://randomuser.me/api/portraits/lego/1.jpg";
      // 检查是否已存在
      if (this.friends.some(f => f.name === this.addFriendName.trim())) {
        this.addFriendError = "该昵称已存在";
        return;
      }
      const newFriend = {
        id: Date.now(),
        name: this.addFriendName.trim(),
        avatar,
        lastMsg: "",
        time: "",
        messages: []
      };
      this.friends.push(newFriend);
      this.addFriendName = "";
      this.addFriendAvatar = "";
      this.addFriendError = "";
      this.showAddFriend = false;
      this.selectFriend(newFriend);
    },
    handleToolClick(idx, tool) {
      this.activeTool = idx;
      this.chat = false;
      this.showAddFriend = false;
      this.showFriendRequest = false;
      this.showContacts = false;
      if (tool.name === "通讯录") {
        this.showContacts = true;
        this.queryContactList();
      }
      if (tool.name === "添加好友") {
        this.showAddFriend = true;
      }
      if (tool.name == "聊天") {
        this.fetchLatestMessage();
        this.chat = true;
      }
      if (tool.name == "好友申请") {
        this.fetchFriendRequests();
        this.showFriendRequest = true;
      }
      // 切换时自动调整宽度
      const minWidth = this.minCenterWidths[tool.name] || 200;
      if (this.centerWidth < minWidth) {
        this.centerWidth = minWidth;
      }
    },
    selectFriend(friend) {
      //查询聊天记录
      this.activeFriend = friend;
      this.fetchHistoryMessage(friend.userId);
      this.$nextTick(this.scrollToBottom);
    },
    fetchHistoryMessage(friendUserId) {
      queryChatHistory(friendUserId).then(response => {
        if (isSuccess(response)) {
          // 假设 response.data 是消息数组
          const messages = response.data.rows.reverse().map(item => ({
            message: item.msg, // 或者 item.message，看后端字段
            isSender: item.sender
          }));
          this.friendMap[friendUserId]={latestMessage : messages};
          // 深拷贝 friendMap，然后替换
          const newMap = { ...this.friendMap };
          newMap[friendUserId] = { latestMessage: messages };
          this.friendMap = newMap;
          console.log("历史记录"+JSON.stringify(this.friendMap[friendUserId]))
        }
      });
    },
    sendMessage() {
      const user = this.$store.state.user;
      if (this.input.trim() && this.activeFriend) {
        console.log("ws的状态是", this.ws.readyState)
        if (!this.ws || this.ws.readyState === WebSocket.CLOSED) {
          this.initWebSocket()
        }
        if (this.ws.readyState === WebSocket.OPEN) {
          this.dataContent.chatMsg.msg = this.input
          this.dataContent.chatMsg.msgType = '1'
          this.dataContent.chatMsg.receiverId = this.activeFriend.userId
          this.dataContent.chatMsg.senderId = user.id
          console.log("发送信息" + this.input)
          this.ws.send(JSON.stringify(this.dataContent));
        }
        this.ws.addEventListener('open', () => {
          this.dataContent.chatMsg.msg = this.input
          this.dataContent.chatMsg.msgType = '1'
          this.dataContent.chatMsg.receiverId = this.activeFriend.userId
          this.dataContent.chatMsg.senderId = user.id
          console.log("发送信息" + this.input)
          this.ws.send(JSON.stringify(this.dataContent));
        })
        this.input = "";
      }
    },
    initWebSocket() {
      if (this.ws) {
        this.ws.close()
      }
      this.ws = new WebSocket(getWsUrl())
      const user = this.$store.state.user;
      this.dataContent.chatMsg.msgType = '0'
      this.dataContent.chatMsg.senderId = user.id
      this.ws.onopen = () => {
        console.log("websocket已开", this.ws.readyState);
        console.log("发送初始化socket信息")
        this.ws.send(JSON.stringify(this.dataContent));
      }
      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data)
        console.log("收到消息" + message.msg)
        const user = this.$store.state.user;
        console.log("当前用户id" + user.id)
        console.log("消息的发送人id:" + message.senderId)
        const isSender = String(user.id) === String(message.senderId);
        const friendId = String(user.id) === String(message.senderId) ? message.receiverId : message.senderId;
        const data = { message: message.msg, isSender: isSender };
        // 深拷贝 friendMap，然后替换
        const newMap = { ...this.friendMap };
        if (!newMap[friendId]) {
          newMap[friendId] = { latestMessage: [data] };
        } else {
          newMap[friendId].latestMessage = [
            ...newMap[friendId].latestMessage,
            data
          ];
        }
        this.friendMap = newMap;
        console.log("收到消息后的map" + friendId + ":" + JSON.stringify(this.friendMap[friendId]));
        this.$nextTick(this.scrollToBottom);
      }
      this.ws.onerror = (err) => {
        console.error("WebSocket 错误：", err);
      };
    },
    scrollToBottom() {
      const chat = this.$refs.chatMessages;
      if (chat) {
        chat.scrollTop = chat.scrollHeight;
      }
    },
    getNowTime() {
      const d = new Date();
      return d.getHours().toString().padStart(2, "0") + ":" + d.getMinutes().toString().padStart(2, "0");
    },
    fetchFriendRequests() {
      // TODO: 替换为实际API
      queryFriendRequest().then(response => {
        if (isSuccess(response)) {
          this.friendRequests = response.data
        }
      })
    },
    acceptRequest(req) {
      // TODO: 调用同意API
      executeFriendRequest({ id: req.id, executeType: 1 }).then(response => {
        if (isSuccess(response)) {
          this.$modal.msgSuccess('已同意 ' + req.nickName + ' 的好友申请');
        }
      })
      this.fetchFriendRequests()
      this.showRemarkDialogVisible = false;
    },
    rejectRequest(req) {
      executeFriendRequest({ id: req.id, executeType: 2 }).then(response => {
        if (isSuccess(response)) {
          this.$modal.msgSuccess('已拒绝 ' + req.nickName + ' 的好友申请');
        }
      })
      this.fetchFriendRequests()
      this.showRemarkDialogVisible = false;
    },
    startDrag(type) {
      if (type !== 'center') return;
      this.dragging = true;
      this.dragStartX = event.clientX;
      this.centerStart = this.centerWidth;
      document.addEventListener('mousemove', this.onDrag);
      document.addEventListener('mouseup', this.stopDrag);
    },
    onDrag(e) {
      if (!this.dragging) return;
      const dx = e.clientX - this.dragStartX;
      this.centerWidth = Math.max(this.currentMinCenterWidth, Math.min(600, this.centerStart + dx));
    },
    stopDrag() {
      this.dragging = false;
      document.removeEventListener('mousemove', this.onDrag);
      document.removeEventListener('mouseup', this.stopDrag);
    },
    async queryContactList() {
      queryFriend().then(response => {
        if (isSuccess(response)) {
          this.contactList = response.data
        }
      })
    },
  },
  created() {
    if (this.friends.length > 0) {
      this.activeFriend = this.friends[0];
    }
  },
  mounted() {
    this.initWebSocket();
    this.fetchLatestMessage();
  }
};
</script>

<style>
@import url('//at.alicdn.com/t/c/font_4244842_2w7k8w2v7k.css');

/* iconfont 示例，可换成你自己的 */
.add-friend-simple {
  padding: 32px 24px;
}

.remark-dialog-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remark-dialog {
  background: #fff;
  border-radius: 8px;
  padding: 24px 32px;
  min-width: 320px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.15);
}

.remark-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  position: relative;
}

.remark-close {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 22px;
  color: #888;
  cursor: pointer;
  padding: 0 8px;
  line-height: 1;
  transition: color 0.2s;
}

.remark-close:hover {
  color: #e74c3c;
}

.remark-content {
  font-size: 15px;
  color: #333;
  margin-bottom: 18px;
  word-break: break-all;
}

.remark-actions {
  display: flex;
  gap: 12px;
}

.remark-actions button {
  padding: 6px 18px;
  border: none;
  border-radius: 4px;
  background: #07c160;
  color: #fff;
  font-size: 15px;
  cursor: pointer;
}

.remark-actions button:last-child {
  background: #b2b2b2;
}

.search-user-input {
  width: 100%;
  padding: 10px 14px;
  border-radius: 6px;
  border: 1px solid #e5e5e5;
  font-size: 16px;
  margin-bottom: 24px;
  outline: none;
}

.searched-user-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.searched-user-info .avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
}

.searched-user-info .name {
  font-size: 18px;
  font-weight: 500;
}

.searched-user-info button {
  background: #07c160;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 8px 18px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.searched-user-info button:disabled {
  background: #b2b2b2;
  cursor: not-allowed;
}

.already-friend {
  color: #888;
  font-size: 14px;
}

.error {
  color: #e74c3c;
  margin-top: 12px;
  text-align: center;
}

.layout {
  display: flex;
  height: 100vh;
  width: 100vw;
}

.sidebar {
  width: 68px;
  min-width: 68px;
  max-width: 68px;
  background: #232323;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 0;
  height: 100%;
  overflow: visible !important;
}

.sidebar aside {
  width: 100%;
  height: 100%;
  background: inherit;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 16px;
}

.drag-bar {
  width: 6px;
  cursor: col-resize;
  background: #e0e0e0;
  z-index: 10;
}

.center {
  min-width: 180px;
  max-width: 900px;
  transition: flex-basis 0.1s;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 0 8px #e5e5e5;
  display: flex;
  flex-direction: column;
}

.chat-panel {
  flex: 1;
  min-width: 0;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
  position: relative;
}

.tool-btn {
  width: 48px;
  height: 48px;
  margin-bottom: 16px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #b2b2b2;
  font-size: 26px;
  position: relative;
  cursor: pointer;
  background: transparent;
  border: none;
  transition: background 0.2s, color 0.2s;
}

.tool-btn.active,
.tool-btn:hover {
  background: rgba(255, 255, 255, 0.18);
  color: #07c160;
}

.tooltip {
  display: none;
  position: absolute;
  left: 70px;
  top: 50%;
  transform: translateY(-50%);
  background: #222;
  color: #fff;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  white-space: nowrap;
  z-index: 9999;
  pointer-events: none;
}

.tool-btn:hover .tooltip {
  display: block;
}

.friends-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
  min-width: 0;
}

.header {
  width: 100%;
  height: 56px;
  line-height: 56px;
  font-size: 22px;
  font-weight: bold;
  color: #222;
  padding-left: 24px;
  border-bottom: 1px solid #ededed;
  background: #f7f7f7;
}

.search-bar {
  width: 100%;
  box-sizing: border-box;
  padding: 12px 20px;
  border-bottom: 1px solid #ededed;
  background: #fafafa;
}

.search-bar input {
  width: 100%;
  box-sizing: border-box;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #e5e5e5;
  font-size: 15px;
  outline: none;
}

.list {
  flex: 1;
  overflow-y: auto;
  width: 100%;
  min-width: 0;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 14px 20px;
  border-bottom: 1px solid #f2f2f2;
  cursor: pointer;
  transition: background 0.2s;
}

.friend-item.active,
.friend-item:hover {
  background: #e5f8ef;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  margin-right: 16px;
}

.info {
  flex: 1;
  min-width: 0;
}

.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.name {
  font-size: 17px;
  font-weight: 500;
  color: #222;
}

.time {
  font-size: 13px;
  color: #b2b2b2;
}

.last-msg {
  font-size: 15px;
  color: #888;
  margin-top: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 聊天面板 */
.chat-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 85%;
  padding: 18px 12px;
}

.chat-header {
  height: 56px;
  display: flex;
  align-items: center;
  padding: 0 24px;
  background: #f7f7f7;
  border-bottom: 1px solid #ededed;
  font-size: 18px;
  font-weight: bold;
}

.chat-header .avatar {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  margin-right: 12px;
}

.chat-messages {
  height: 500px;
  overflow-y: auto;
  padding: 18px 24px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: #f8f8f8;
}

.message {
  max-width: 60%;
  padding: 8px 14px;
  border-radius: 8px;
  font-size: 15px;
  word-break: break-all;
  margin-bottom: 4px;
}

.message.sent {
  align-self: flex-end;
  background: #95ec69;
  color: #222;
}

.message.received {
  align-self: flex-start;
  background: #f1f1f1;
  color: #222;
}

.chat-input {
  display: flex;
  padding: 14px 24px;
  border-top: 1px solid #ededed;
  background: #fafafa;
}

.chat-input input {
  flex: 1;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  padding: 8px;
  font-size: 15px;
  outline: none;
}

.chat-input button {
  margin-left: 8px;
  background: #07c160;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 8px 18px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.chat-input button:disabled {
  background: #b2b2b2;
  cursor: not-allowed;
}

.chat-input button:hover:enabled {
  background: #13ce66;
}

.chat-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #bbb;
  font-size: 18px;
  letter-spacing: 2px;
}

.add-friend-dialog-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-friend-dialog {
  background: #fff;
  border-radius: 8px;
  padding: 24px 32px;
  min-width: 320px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.15);
}

.add-friend-dialog .dialog-header {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
}

.add-friend-dialog .dialog-body {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.add-friend-dialog .avatar {
  width: 56px;
  height: 56px;
  border-radius: 8px;
  margin-bottom: 8px;
}

.add-friend-dialog .user-info .name {
  font-size: 18px;
  font-weight: 500;
}

.add-friend-dialog .input-group {
  width: 100%;
  margin: 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.add-friend-dialog .input-group label {
  width: 64px;
  text-align: right;
  color: #666;
}

.add-friend-dialog .input-group input {
  flex: 1;
  padding: 6px 10px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 15px;
}

.add-friend-dialog .dialog-footer {
  margin-top: 18px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.add-friend-dialog .dialog-footer button {
  padding: 6px 18px;
  border: none;
  border-radius: 4px;
  background: #07c160;
  color: #fff;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.add-friend-dialog .dialog-footer button:last-child {
  background: #b2b2b2;
}

.friend-request-list {
  width: 100%;
  box-sizing: border-box;
  padding: 24px 0;
}

.friend-request-item {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  background: #f7f7f7;
  border-radius: 8px;
  margin-bottom: 18px;
  padding: 14px 18px;
  box-shadow: 0 1px 4px #eee;
}

.friend-request-item .avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  margin-right: 16px;
}

.friend-request-item .info {
  flex: 1;
  min-width: 0;
}

.friend-request-item .name {
  font-size: 17px;
  font-weight: 500;
  color: #222;
}

.friend-request-item .msg {
  font-size: 15px;
  color: #888;
  margin-top: 4px;
}

.friend-request-item .meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
  font-size: 12px;
}

.friend-request-item .meta .time {
  color: #999;
}

.friend-request-item .meta .status {
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
}

.friend-request-item .meta .status.pending {
  background-color: #e6f7ff;
  color: #1890ff;
}

.friend-request-item .meta .status.accepted {
  background-color: #f6ffed;
  color: #52c41a;
}

.friend-request-item .meta .status.rejected {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.friend-request-item .actions {
  display: flex;
  gap: 10px;
}

.friend-request-item .actions button {
  padding: 6px 16px;
  border: none;
  border-radius: 4px;
  background: #07c160;
  color: #fff;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.friend-request-item .actions button:last-child {
  background: #e74c3c;
}

.friend-request-list .empty {
  color: #bbb;
  text-align: center;
  margin-top: 40px;
  font-size: 16px;
}

.friend-request-item .remark {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  cursor: pointer;
  color: #1890ff;
  margin-top: 10px;
  margin-bottom: 4px;
  font-size: 14px;
  line-height: 1.5;
}

.contacts-list {
  overflow-y: auto;
  padding: 24px 0;
  height: 100%;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #f2f2f2;
}

.contact-item .avatar {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  margin-right: 16px;
}

.contact-item .info {
  flex: 1;
}

.contact-item .name {
  font-size: 16px;
  font-weight: 500;
}

.contact-item button {
  background: #07c160;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 6px 16px;
  font-size: 14px;
  cursor: pointer;
}

.contact-group {
  margin-bottom: 18px;
}

.group-title {
  font-size: 15px;
  font-weight: bold;
  color: #07c160;
  padding: 4px 20px 2px 20px;
  background: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 4px;
}
</style>